﻿using System.Collections.Generic;

using UnityEngine;

[CreateAssetMenu]
public class UGUIAtlas : ScriptableObject
{
    [SerializeField, HideInInspector]
    protected Texture texture;

    [SerializeField, HideInInspector]
    protected List<Sprite> sprites;

    protected Dictionary<string, Sprite> spriteDict = null;

    protected Dictionary<string, Sprite> SpriteDict
    {
        get
        {
            if (spriteDict == null)
            {
                spriteDict = new Dictionary<string, Sprite>(sprites.Count);
                foreach (var sprite in sprites)
                {
                    if (sprite != null)
                    {
                        spriteDict[sprite.name] = sprite;
                    }
                }
            }
            return spriteDict;
        }
    }

    public Sprite GetSprite(string spriteName)
    {
        if (string.IsNullOrEmpty(spriteName))
        {
            GLog.Error("GetSprite Argument is NULL");
        }
        if (SpriteDict.ContainsKey(spriteName))
        {
            return spriteDict[spriteName];
        }
        return null;
    }

    public Sprite GetSpriteAt(int index)
    {
        return (sprites != null && index >= 0 && index < sprites.Count) ? sprites[index] : null;
    }

    public Texture GetTexture()
    {
        return texture;
    }

    public int GetSpriteCount()
    {
        return sprites != null ? sprites.Count : 0;
    }

#if UNITY_EDITOR

    public void EditorSetTexture(Texture texture)
    {
        this.texture = texture;
    }

    public void EditorSetSprites(List<Sprite> sprites)
    {
        this.sprites = new List<Sprite>(sprites);
        spriteDict = new Dictionary<string, Sprite>(sprites.Count);
        foreach (var sprite in sprites)
        {
            spriteDict[sprite.name] = sprite;
        }
    }
#endif
}